package cn.yunhe.proxy.dynamic.interceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import cn.yunhe.proxy.dynamic.dao.Transaction;

/**
 * JDK的动态代理, 代理对象和目标对象实现了共同的接口, 拦截器必须实现InvocationHanlder接口
 * 
 * @author ZSL
 *
 */
public class MyInterceptor implements InvocationHandler {

	private Object target;
	private Transaction transaction;

	public MyInterceptor(Object target, Transaction transaction) {
		super();
		this.target = target;
		this.transaction = transaction;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		if (method.getName().equals("savePerson") || method.getName().equals("deletePerson")
				|| method.getName().equals("updatePerson")) {
			// 开启事物
			transaction.beginTransaction();

			Object result = method.invoke(target, args);// 执行目标对象的目标方法

			// 提交事物
			transaction.commit();
			return result;
		} else {
			return method.invoke(target, args);
		}

	}

	/**
	 * 获取目标对象的代理对象
	 * 
	 * @return 代理对象
	 */
	public Object ss() {
		return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(),
				this);
	}

}
